<template>
  <view>
    <PosterShow
      ref="myCanvasRef"
      :width="350"
      :height="605"
      @save="savePosterFn"
      @close="closeMarks"
    />
  </view>
</template>

<script>
import PosterShow from './PosterShow.vue'
import bg from '@/static/invite/xzbg.png'
import shareLogo from '@/static/invite/link.png'
import a0 from '@/static/invite/weixin.png'
import a1 from '@/static/invite/pyq.png'
import { getSettingIsOk, goAuthorize, isShowOpenSetting } from '@/utils/miniscope'

export default {
  components: {
    PosterShow
  },
  props: {
    isStart: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      // 最初为375，现改为300
      ratioW: 350 / 375,
      ratioH: 560 / 605
    }
  },
  watch: {
    isStart(newVal) {
      if (newVal) {
        this.createPoster()
      } else {
        this.closeMarks()
      }
    }
  },
  mounted() {
    if (this.isStart) {
      this.createPoster()
    }
  },
  methods: {
    getAvatar(avatar) {
      switch (Number(avatar)) {
        case 1:
          return a1
        default:
          return a0
      }
    },
    getOption(codeurl) {
      // const info = uni.getStorageSync('userinfo')
      const info = {
        driverId: '1111',
        driverName: '****',
        driverTel: '2222',
        driverAvatar: '0',
        driverAddress: '银河',
        carNumber: null,
        vehicleType: null,
        approvedWeight: null,
        driverAuthStatus: 0,
        vehicleAuthStatus: 0,
      }

      // 配置项
      return [
        {
          type: 'image',
          url: bg,
          left: 12,
          top: 20,
          width: 350,
          height: 500,
        },
      ]
    },
    // 调用myCanvas的onDraw方法，绘制并保存
    async createPoster() {
      // 二维码图片
      const codeUrl = 'https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/uniCloud.png'
      this.$refs.myCanvasRef.onDraw(this.getOption(codeUrl), () => {})
    },
    // 保存操作
    savePosterToAlbum() {
      this.$refs.myCanvasRef.onSave((url) => {
        console.log('app保存', url)
        this.$emit('success')
      })
    },
    async savePosterFn() {
      // #ifdef MP-WEIXIN
      // 获取权限状态
      const settingStatus = await getSettingIsOk('writePhotosAlbum')
      // 已授权
      if (settingStatus) return this.savePosterToAlbum()
      // 拒绝授权
      if (settingStatus === false) return isShowOpenSetting('writePhotosAlbum', this.savePosterToAlbum)
      // 第一次未授权
      await goAuthorize('writePhotosAlbum', this.savePosterToAlbum, this.savePosterToAlbum)
      // #endif

      // #ifdef APP-PLUS
      this.savePosterToAlbum()
      // #endif

      // #ifdef H5
      console.log('h5保存可使用第三方插件')
      // #endif
    },
    closeMarks() {
      this.$emit('close')
    }
  }
}
</script>

<style lang="scss" scoped></style>